﻿using System;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Southern.Common;
using Southern.Common.Utilities;
using Southern.Models.Southern.Partials;

namespace Southern.Controllers
{
    public class UploadImageController : BaseController
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            if (Request.IsAjaxRequest())
            {
                return PartialView();
            }
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(UploadImageInfo model)
        {
            //Check if all simple data annotations are valid
            if (ModelState.IsValid)
            {
                //Prepare the needed variables
                Bitmap original = null;
                var name = "newimagefile";
                var errorField = string.Empty;

                if (model.IsUrl)
                {
                    errorField = "Url";
                    name = Utility.GetUrlFileName(model.Url);
                    original = Utility.GetImageFromUrl(model.Url);
                }
                else if (model.IsFlickr)
                {
                    errorField = "Flickr";
                    name = Utility.GetUrlFileName(model.Flickr);
                    original = Utility.GetImageFromUrl(model.Flickr);
                }
                else if (model.File != null) // model.IsFile
                {
                    errorField = "File";
                    Regex reg = new Regex(@"\s*");
                    string fileName = reg.Replace(model.File.FileName, "");
                    name = Path.GetFileNameWithoutExtension(fileName);
                    original = Bitmap.FromStream(model.File.InputStream) as Bitmap;
                }

                //If we had success so far
                if (original != null)
                {
                    var img = Utility.CreateImage(original, model.X, model.Y, model.Width, model.Height);

                    //Demo purposes only - save image in the file system
                    string curDateString = DateTime.Now.Year + "_" + DateTime.Now.Month + "_" +
                                                DateTime.Now.Day;
                    string filename = SecurityUtility.RandomString(10) + "_" + name;
                    string uploadpath = "~/Content/images/Uploads/Users/" + 0 + "/" + curDateString + "/";
                    if (!Directory.Exists(Server.MapPath(uploadpath)))
                        Directory.CreateDirectory(Server.MapPath(uploadpath));
                    var fn = Server.MapPath(uploadpath + filename + ".png");
                    img.Save(fn, System.Drawing.Imaging.ImageFormat.Png);

                    //Redirect to partialview
                    return PartialView();
                }
                else //Otherwise we add an error and return to the (previous) view with the model data
                    ModelState.AddModelError(errorField, "Your upload did not seem valid. Please try again using only correct images!");
            }

            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PreviewImage()
        {
            var bytes = new byte[0];
            ViewBag.Mime = "image/png";

            if (Request.Files.Count == 1)
            {
                bytes = new byte[Request.Files[0].ContentLength];
                Request.Files[0].InputStream.Read(bytes, 0, bytes.Length);
                ViewBag.Mime = Request.Files[0].ContentType;
            }

            ViewBag.Message = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
            return PartialView();
        }
    }
}
